package com.sunshine.litemusic.fragment.recommend;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author sunshine
 * @date 2020/5/28
 * 主活动的viewModel，主要负责数据的处理和储存
 */
public class RecommendViewModel extends AndroidViewModel {

    private final static String TAG = "SearchViewModel";
    private MutableLiveData<ArrayList<RecommendModel.RecommendBean>> recommendBeanMutableLiveData;

    public RecommendViewModel(@NonNull Application application) {
        super(application);
        recommendBeanMutableLiveData = new MutableLiveData<>();
        recommendBeanMutableLiveData.setValue(null);
    }

    MutableLiveData<ArrayList<RecommendModel.RecommendBean>> getRecommendBeanMutableLiveData() {
        return recommendBeanMutableLiveData;
    }

    void getMusic(){
        String url = "https://api.imjad.cn/cloudmusic/?type=playlist&id=497083385";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                resolveMusicJSON(response.body().string());
                Log.e(TAG, "onResponse");
            }
        });
    }

    private void resolveMusicJSON(String html){
        System.out.println(html);
        try{
            JsonArray jsonArray = JsonParser
                    .parseString(html)
                    .getAsJsonObject()
                    .getAsJsonArray("result");
            ArrayList<RecommendModel.RecommendBean> recommendBeanArrayList = new ArrayList<>();
            for (JsonElement jsonElement : jsonArray){
                RecommendModel.RecommendBean recommendBean = new Gson().fromJson(jsonElement, RecommendModel.RecommendBean.class);
                recommendBeanArrayList.add(recommendBean);
            }
            recommendBeanMutableLiveData.postValue(recommendBeanArrayList);   //这里不能用setValue因为它只能在主线程调用
        }catch (Exception e){
            Log.e(TAG, e.toString());
        }
    }
}
